import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';

import { useAppStore } from "@/store";
import { buildVueRouter } from "@/utils/menu";
import createRouteGuard from './guard';
import { DEFAULT_ROUTE } from "./constants";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: DEFAULT_ROUTE.fullPath,
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      beforeEnter: async (to, from, next) => {
        const appStore = useAppStore();
        if (
          !appStore.appAsyncMenus.length
        ) {
          await appStore.fetchServerMenuConfig();
          if (!appStore.appAsyncMenus.length) {
            next()
          } else {
            // @ts-ignore
            buildVueRouter(appStore.appAsyncMenus).forEach(router.addRoute)
            await router.push({
              path: to.fullPath
            })
          }
        }
        next()
      },
      component: () => import('@/views/not-found/index.vue'),
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});

createRouteGuard(router);

export default router;
